package com.chj.consumer_balance.ackfalse;

import com.chj.consumer_balance.getmessage.GetMessageProducer;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeoutException;

/**
 * 消息者不对消息进行确认
 */
public class AckFalseConsumerA {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("10.200.169.5");
        connectionFactory.setVirtualHost("chj_vhost");
        connectionFactory.setUsername("chj");
        connectionFactory.setPassword("123456");
        // 创建连接
        Connection connection = connectionFactory.newConnection();
        final Channel channel = connection.createChannel();
        // 创建交换器 BuiltinExchangeType.DIRECT == direct
        channel.exchangeDeclare(GetMessageProducer.EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        // 声明一个队列
        final String queueName = "focuserror";
        channel.queueDeclare(queueName, false, false, false, null);
        //只关注error级别的日志，然后记录到文件中去。
        String routekey = "error";
        channel.queueBind(queueName, GetMessageProducer.EXCHANGE_NAME, routekey);
        System.out.println(" [*] Waiting for messages......");
        final Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                try {
                    String message = new String(body, "UTF-8");
                    System.out.println("Received["+envelope.getRoutingKey()+"]"+message);
                    // 确认
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    // 拒绝
                }
            }
        };
        /*消费者正式开始在指定队列上消费消息*/
        //TODO 这里第二个参数是自动确认参数，如果是false则是手动确认
        channel.basicConsume(queueName,false,consumer);
    }
}
